import { defineStore } from 'pinia'
import { store } from '../index.js'

export type ManageRouterType = {
    /**
     * code
     */
    code: string;

    /**
     * 标题
     */
    title: string;
    /**
     * 图标
     */
    fileIdOfIcon: number;
    /**
     * 路径
     */
    path: string;

    /**
     * 组件路径
     */
    componentPath: string;


    /**
     * 子菜单
     */
    children: ManageRouterType[];
}

export interface IManageMenuStore {
    /**
     * 管理菜单列表
     */
    manageRouterList: ManageRouterType[];

    /**
     * 面包屑集合
     */
    breadCrumbList: ManageRouterType[];

    /**
     * 现在菜单
     */
    nowMenu: any;

}

const useManageRouterStore = defineStore({
    id: 'manageMenu',
    state: (): IManageMenuStore => ({
        manageRouterList: [],
        breadCrumbList: [],
        nowMenu: {
            "code": "setting",
            "fileIdOfIcon": "508182879535109",
            "gmtCreate": 1706233291276,
            "gmtModified": 1706233326828,
            "id": 508182895771653,
            "parentCode": "system",
            "path": "/system/setting",
            "priority": 971,
            "title": "系统设置"
        }
    }),
    getters: {
        getBreadCrumbList(): IManageMenuStore['breadCrumbList'] {
            return this.breadCrumbList;
        },
        getNowMenu(): IManageMenuStore['nowMenu'] {
            return this.nowMenu;
        },
    },
    actions: {
        setNowMenu(menu: string) {
            this.nowMenu = menu;
            localStorage.setItem("nowMenu", JSON.stringify(menu));
            this.addBreadCrumbItem(menu);
        },
        setBreadCrumbList(list: IManageMenuStore['breadCrumbList']) {
            this.breadCrumbList = list;
        },
        addBreadCrumbItem(item: ManageRouterType) {
            // 如果已经存在，则删除之前的
            let index = this.breadCrumbList.findIndex((x) => x.code === item.code);
            if (index >= 0) {
                this.breadCrumbList.splice(index, 1);
            }
            // 超过10个，删除第一个
            if (this.breadCrumbList.length >= 10) {
                this.breadCrumbList.shift();
            }
            this.breadCrumbList.push(item);
            localStorage.setItem("breadCrumbList", JSON.stringify(this.breadCrumbList));
        },
    }
});

let localNowMenu = localStorage.getItem("nowMenu");
// 判断是不是json字符串
if (localNowMenu&&localNowMenu.indexOf("{")>=0) {
    useManageRouterStore(store).setNowMenu(JSON.parse(localNowMenu));
}

const useManageMenuStoreWithOut = () => {
    return useManageRouterStore(store);
}

export {
    useManageRouterStore,
    useManageMenuStoreWithOut
}

